<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/9/12
 * Time: 18:33
 *  生产订单控制器
 */
require('env.php');
require('init.inc.php');

$data = $_POST;

//查询产品表，看看product_id是否合法
$prod = Products::getProductById($data['product_id']);
if (!$prod) {
    exit("<script type='text/javascript'>alert('沒有該物品')</script>");
}


$product = OrderProduct::getAllBuyProds($_COOKIE['ansyuserid']);
//合法话插入数据库记录
$input_data = array('userid' => $_COOKIE['ansyuserid'], 'product_id' => $data['product_id'], 'product_nums' => $data['num'], 'size' => $data['size'], 'color' => $data['color'], 'createtime' => time(), 'modifytime' => time());

$id = 0;
if ($product) {
    foreach ($product as $p) {
        if (!$p['order_sn']) {
            if ($p['iddel'] == 1) {
                if ($p['product_id'] == $data['product_id']) {
                    OrderProduct::delete($p['id']);
                    $input_new_data = array('userid' => $_COOKIE['ansyuserid'], 'product_id' => $data['product_id'], 'product_nums' => ($data['num'] + $p['product_nums']), 'size' => $data['size'], 'color' => $data['color'], 'createtime' => time(), 'modifytime' => time());
                    $id = OrderProduct::add($input_new_data);
                    break;
                } else {
                    $input_new_data = array('userid' => $_COOKIE['ansyuserid'], 'product_id' => $data['product_id'], 'product_nums' => $data['num'], 'size' => $data['size'], 'color' => $data['color'], 'createtime' => time(), 'modifytime' => time());
                    $id = OrderProduct::add($input_new_data);
                    break;
                }
            } else {
                OrderProduct::delete($p['id']);
                $id = OrderProduct::add($input_data);
                break;
            }
        } else {
            $id = OrderProduct::add($input_data);
            break;
        }
    }
} else {
    $id = OrderProduct::add($input_data);
}


exit(json_encode(array("msg" => "true", "OrderProdDbId" => $id)));

